package aom.example.security.controller;

import aom.example.security.IsAdmin;
import aom.example.security.domain.SelfUserEntity;
import aom.example.security.domain.SysMenuEntity;
import aom.example.security.domain.SysUserEntity;
import aom.example.security.domain.vo.UserVo;
import aom.example.security.service.SysMenuService;
import aom.example.security.service.SysUserService;
import aom.example.security.util.ResultUtil;
import bom.example.common.common.Results;
import bom.example.common.jsonfilter.SerializeField;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/6/11 15:27
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/user")
@Api(tags = {"用户服务接口"})
public class UserController {


    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("login")
    @ApiOperation("登入接口")
    public JSONObject logincontroller(@ApiParam("密码")@RequestParam("password")String password,
                                      @ApiParam("账号")@RequestParam("username")String username
                                      ){
        return Results.success();
    }

    /**
     * 用户端信息
     * @Author Sans
     * @CreateTime 2019/10/2 14:52
     * @Return Map<String,Object> 返回数据MAP
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    @ApiOperation("登入信息")
    public Map<String,Object> userLogin(){
        Map<String,Object> result = new HashMap<>();
        SelfUserEntity userDetails = (SelfUserEntity) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        result.put("title","用户端信息");
        result.put("data",userDetails);
        return ResultUtil.resultSuccess(result);
    }

    /**
     * 拥有USER角色和sys:user:info权限可以访问
     * @Author Sans
     * @CreateTime 2019/10/2 14:22
     * @Return Map<String,Object> 返回数据MAP
     */
    @PreAuthorize("hasRole('USER') and hasPermission('/user/menuList','sys:user:info')")
    @RequestMapping(value = "/menuList",method = RequestMethod.GET)
    public Map<String,Object> sysMenuEntity(){
        Map<String,Object> result = new HashMap<>();
        List<SysMenuEntity> sysMenuEntityList = sysMenuService.list();
        result.put("title","拥有USER角色和sys:user:info权限可以访问");
        result.put("data",sysMenuEntityList);
        return ResultUtil.resultSuccess(result);
    }

    @PostMapping("/getUserList")
    @ApiOperation("查询用户列表")
    public JSONObject getUserListController(@ApiParam("页码") @RequestParam(value = "pageNum",defaultValue = "0")Integer page,
                                            @ApiParam("条数")@RequestParam(value = "pageSize",defaultValue = "10")Integer size,
                                            @ApiParam("关键字")@RequestParam(value = "keyword",required = false)String keyword){
        LambdaQueryWrapper<SysUserEntity> lambdaQueryWrapper=new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(keyword)){
            lambdaQueryWrapper.or().like(SysUserEntity::getRealname,keyword);
            lambdaQueryWrapper.or().like(SysUserEntity::getAddress,keyword);
            lambdaQueryWrapper.or().like(SysUserEntity::getUsername,keyword);
        }
        Page page1=new Page(page,size);
        IPage<SysUserEntity> iPage=sysUserService.page(page1,lambdaQueryWrapper);
        JSONObject obj=new JSONObject();
        obj.put("code",0);
        obj.put("msg","success");
        obj.put("rows",iPage.getRecords());
        obj.put("total",iPage.getTotal());
        return obj;
    }

    @ApiOperation("用户新增")
    @IsAdmin
    @PostMapping("adduser")
    public JSONObject addUserController(@RequestBody UserVo userVo){
        SysUserEntity sysUserEntity=sysUserService.selectUserByName(userVo.getUsername());
        if(sysUserEntity!=null){
            return ResultUtil.resultCodeJSON(1,"账号已经存在");
        }
        if(!userVo.getAgainpassword().equals(userVo.getPassword())){
            return ResultUtil.resultCodeJSON(1,"两次密码不一致");
        }
        SysUserEntity userEntity=new SysUserEntity();

        BeanUtils.copyProperties(userVo,userEntity);
        userEntity.setPassword(bCryptPasswordEncoder.encode(userEntity.getPassword()));
        sysUserService.save(userEntity);
        return ResultUtil.resultCodeJSON(0,"添加成功");
    }

    @PostMapping("getUserInfoList")
    public JSONObject getUserInfoListController(@ApiParam("页码")@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                                @ApiParam("条数")@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                                @ApiParam("关键字") @RequestParam(value = "keyword",required = false) String keyword){
        List<Map<String, Object>> mapList=sysUserService.selectUserInfoUserList(pageNum,pageSize,keyword);
        Integer count=sysUserService.selectCountUserInfoUserList(keyword);
        return Results.success(mapList,count);
    }

    @PostMapping("getRoleMenuList")
    public JSONObject getRoleMenuListController(@ApiParam("页码")@RequestParam(value = "pageNum") Integer pageNum,
                                                @ApiParam("条数")@RequestParam(value = "pageSize")Integer pageSize){
        return Results.success();
    }

    @ApiOperation("获取用户信息")
    @PostMapping("getUerInfo/{id}")
    public JSONObject getUserInfo(@PathVariable("id")String id){
        SysUserEntity sysUserEntity=sysUserService.getById(id);
        sysUserEntity.setPassword("");
        return Results.success(sysUserEntity);
    }

    @ApiOperation("用户信息修改")
    @PostMapping("updateUser")
    public JSONObject updateUserControler(@RequestBody UserVo userVo){
        SysUserEntity sysUserEntity=new SysUserEntity();
        BeanUtils.copyProperties(userVo,sysUserEntity);
        sysUserService.updateById(sysUserEntity);
        return Results.success();
    }



}
